package org.zffc.boot.starter.vault.util;

import org.zffc.boot.starter.vault.domain.KeyPair;
import org.zffc.boot.starter.vault.enums.KeyLengthEnum;

import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.KeyPairGenerator;
import java.security.spec.ECGenParameterSpec;
import java.util.Base64;

import static org.zffc.boot.starter.vault.enums.KeyLengthEnum.AES_128;


/**
 *  密钥生成工具
 */
public class KeyGeneratorUtils {
    /**
     * 根据枚举生成对称密钥（AES）
     */
    public static KeyPair generateSymmetricKey(KeyLengthEnum keyLength) throws Exception {
        if (!keyLength.isSymmetric()) {
            throw new IllegalArgumentException(keyLength + " 不是对称加密算法");
        }
        KeyGenerator keyGenerator = KeyGenerator.getInstance(keyLength.getAlgorithm());
        keyGenerator.init(keyLength.getBits());
        Key key = keyGenerator.generateKey();
        return new KeyPair(key,key);
    }

    /**
     * 根据枚举生成非对称密钥对（RSA/ECC）
     */
    public static KeyPair generateAsymmetricKeyPair(KeyLengthEnum keyLength) throws Exception {
        if (!keyLength.isAsymmetric()) {
            throw new IllegalArgumentException(keyLength + " 不是非对称加密算法");
        }

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyLength.getAlgorithm());

        // 特殊处理ECC算法
        if ("EC".equals(keyLength.getAlgorithm())) {
            ECGenParameterSpec ecSpec = new ECGenParameterSpec(keyLength.getEcCurve());
            keyPairGenerator.initialize(ecSpec);
        } else {
            keyPairGenerator.initialize(keyLength.getBits());
        }

        java.security.KeyPair keyPair = keyPairGenerator.generateKeyPair();
        return new KeyPair(keyPair.getPrivate(),keyPair.getPublic());
    }

    /**
     * 将密钥转为Base64字符串（便于存储）
     */
    public static String encodeKey(Key key) {
        return Base64.getEncoder().encodeToString(key.getEncoded());
    }

    /**
     * 从Base64字符串恢复成byte数组
     */
    public static byte[] base64ToBytes(String base64Key) {
        return Base64.getDecoder().decode(base64Key);
    }

    public static void main(String[] args) throws Exception {
        System.out.println(generateSymmetricKey(AES_128));
    }


}
